import type card from "./cardData/card";
import { checkCard } from "./cardData/card";
import roomData, { checkRoomData } from "./roomData";

function download(filename: string, text: string) {
    let pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);
    pom.click();
}
const ROOM_PRE_FIX = "mania-room:";
const CARD_PRE_FIX = "mania-card:";

async function fileToString(file: File): Promise<string> {
    return await file.text();
}

/**
 * 下载房间数据到文件
 * @param filename - 文件名
 * @param room - 房间数据
 */
export async function roomDownload(filename: string, room: roomData): Promise<void> {
    download(filename, ROOM_PRE_FIX + JSON.stringify(room));
}

/**
 * 下载卡片数据到文件
 * @param filename - 文件名
 * @param card - 卡片数据
 */
export async function cardDownload(filename: string, card: card): Promise<void> {
    download(filename, CARD_PRE_FIX + JSON.stringify(card));
}

async function processFile<T>(files: File[], prefix: string, checkFunction: (data: any) => T | undefined, callBack: (data: T | undefined, file: File) => void): Promise<void> {
    for (const file of files) {
        try {
            const data = await fileToString(file);
            if (data.startsWith(prefix)) {
                const parsedData = JSON.parse(data.substring(prefix.length));
                const result = checkFunction(parsedData);
                callBack(result, file);
            } else {
                callBack(undefined, file);
            }
        } catch (error) {
            console.error(`Error processing file ${file.name}:`, error);
            callBack(undefined, file);
        }
    }
}

/**
 * 上传房间数据文件
 * @param files - 文件数组
 * @param callBack - 回调函数，处理上传的数据
 */
export async function roomUpload(files: File[], callBack: (data: roomData | undefined, file: File) => void): Promise<void> {
    await processFile(files, ROOM_PRE_FIX, checkRoomData, callBack);
}

/**
 * 上传卡片数据文件
 * @param files - 文件数组
 * @param callBack - 回调函数，处理上传的数据
 */
export async function cardUpload(files: File[], callBack: (data: card | undefined, file: File) => void): Promise<void> {
    await processFile(files, CARD_PRE_FIX, checkCard, callBack);
}